package com.lh.glassmuseum;

import com.lh.glassmuseum.service.*;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class HelloApplication extends Application {
    private ScheduledExecutorService scheduler;
    private Stage primaryStage;
    private static final Logger LOGGER = LoggerFactory.getLogger(HelloApplication.class);

    @Override
    public void start(Stage primaryStage) {
        this.primaryStage = primaryStage;
        // 界面构建
        AnchorPane root = ImageService.root;
        // 初始化串口
        boolean result = SerialPortService.initSerialPort();
        if(!result){
            return;
        }
        //添加提示区域
        TipService.createTipArea(root);
        //添加图片
        ImageService.addImg(root);
        //添加输入框
        InputService.constructInput(root);
        //扫描音频文件
        MediaService.loadPlayer();
        //设置窗口
        Scene scene = new Scene(root, 800, 600);
        primaryStage.setScene(scene);
        primaryStage.initStyle(StageStyle.UNDECORATED);  // 隐藏标题栏
        primaryStage.setFullScreen(true);                // 强制全屏
        primaryStage.setAlwaysOnTop(true);               // 窗口置顶
        primaryStage.setFullScreenExitHint("");          // 隐藏退出提示
        primaryStage.setFullScreenExitKeyCombination(KeyCombination.NO_MATCH);  // 禁用ESC退出
        primaryStage.show();


        // 初始化定时任务
        startActivationCheck(5, TimeUnit.SECONDS);
        //窗口状态监听（防止意外最小化）
        primaryStage.iconifiedProperty().addListener((obs, oldVal, newVal) -> {
            if (newVal) primaryStage.setIconified(false);
        });
        //多显示屏适配
        Screen primaryScreen = Screen.getPrimary();
        Rectangle2D bounds = primaryScreen.getBounds();
        primaryStage.setX(bounds.getMinX());
        primaryStage.setY(bounds.getMinY());
        //系统级防护
        //使用JNI调用Windows API禁用Alt+Tab（需配合本地库）
        //通过Java AWT获取独占键盘焦点
//        KeyboardFocusManager.getCurrentKeyboardFocusManager()
//                .addKeyEventDispatcher(e -> {
//                    if (e.getID() == KeyEvent.KEY_PRESSED) {
//                        // 过滤系统组合键
//                    }
//                    return false;
//        });

        // 窗口关闭事件处理
        primaryStage.setOnCloseRequest(e -> {
            shutdownGracefully();
            Platform.exit();
            System.exit(0);
        });
    }


    private void startActivationCheck(long period, TimeUnit unit) {
        scheduler = Executors.newSingleThreadScheduledExecutor();

        // 创建异步校验任务
        Runnable checkTask = () -> CompletableFuture
                .supplyAsync(HttpService::checkToken)
                .thenAccept(valid -> {
                    // 强制窗口置顶
                    primaryStage.setAlwaysOnTop(true);
                    // 焦点重定向（防止系统弹窗干扰）
                    if (!InputService.input.isFocused()) {
                        Platform.runLater(() -> {
                            InputService.input.requestFocus();
                            //光标设置最右侧
//                            InputService.input.positionCaret(InputService.input.getText().length());
                        });
                    }
                    if (!valid) {
                        Platform.runLater(this::handleInvalidLicense);
                    }
                })
                .exceptionally(ex -> {
                    LOGGER.error("心跳定时任务异常",ex);
                    return null;
                });

        // 启动定时任务
        scheduler.scheduleAtFixedRate(
                checkTask,
                0,    // 初始延迟
                period,
                unit
        );
    }

    private void handleInvalidLicense() {
        // 显示警告对话框
        Platform.runLater(() ->{
            //替换logo
            ImageService.setErrorImg();
            //修改提示语言
            TipService.updateDisplay("验票服务器请求失败，请联系技术员");
        }
        );

        // 延迟3秒后退出
//        scheduler.schedule(this::shutdownGracefully, 3, TimeUnit.SECONDS);
    }

    private void shutdownGracefully() {
        try {
            if (scheduler != null) {
                scheduler.shutdownNow();
            }
            if (primaryStage != null) {
                primaryStage.close();
            }
            // 其他资源释放逻辑
        } finally {
            System.exit(1); // 非正常退出码
        }
    }


    public static void main(String[] args) {
        launch();
    }
}